﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Controls.Primitives;
using System.ComponentModel;
using System.Threading;
using System.Windows.Media.Imaging;
using System.Net.NetworkInformation;

namespace ReadManga
{
    public partial class MainPage : PhoneApplicationPage
    {
        private Popup popup;
        private BackgroundWorker backroungWorker;
        WebClient client = new WebClient();
        WebClient client2 = new WebClient();
        WebClient client3 = new WebClient();
        bool loadNewSucess = false;
        bool loadListSucess = false;
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            if (NetworkInterface.GetIsNetworkAvailable() != true)
            {
                MessageBox.Show("Hiện không có kết nối mạng vui lòng kiểm tra và thử lại!");

                return;
            }
            Global.PageNew.PageIndex = 1;
            Global.PageManga.PageIndex = 1;

            ShowSplash();
        }

        // Load data for the ViewModel Items
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {

        }
        private void ShowSplash()
        {
            this.popup = new Popup();
            this.popup.Child = new GUI.LoadingUI();
            this.popup.IsOpen = true;
            StartLoadingData("");
        }
        private void LoadListNew(string content)
        {
            ListMangaNew.Items.Clear();
            string CheckContent = content;
            string line = "";
            line = GetStringBetweenText(CheckContent, "<a href=", "/a>");
            while (line != "")
            {
                
                string Title = HttpUtility.HtmlDecode(GetStringBetweenText(line, "<h3>", "</h3>"));
                string Image = GetStringBetweenText(line, "<img src=\"", "\"").Trim();
                string Description = HttpUtility.HtmlDecode(GetStringBetweenText(line, "<span class=\"soluoc\">", "</span>").Trim());
                GUI.ItemDetails item = new GUI.ItemDetails();
                item.Title = Title;
                if (Title != "" && Image!="")
                {
                    item.Thumbnail.Source = new BitmapImage(new Uri(Image));
                    item.Description = Description;
                    item.UrlImage = Image;
                    item.Url = "http://m.blogtruyen.com" + GetStringBetweenText(line, "\"", "\"");
                    ListMangaNew.Items.Add(item);
                }
                CheckContent = GetStringBetweenText(CheckContent, "<div class=\"clear\">", "");

                line = GetStringBetweenText(CheckContent, "<a href=", "/a>");
            }
        }
        private void StartLoadingData(string Url)
        {

            LoadListNew(Global.PageNew.PageIndex);
            LoadMangaList(Global.PageManga.PageIndex);
            

            backroungWorker = new BackgroundWorker();
            backroungWorker.DoWork += new DoWorkEventHandler(backroungWorker_DoWork);
            backroungWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backroungWorker_RunWorkerCompleted);
            backroungWorker.RunWorkerAsync();
        }
        private void LoadMangaList(int PageIndex)
        {
            Global.PageManga.PageIndex = PageIndex;

            string Url = "http://m.blogtruyen.com/danhsach/?page=" + PageIndex.ToString();
        
            client2.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client2_DownloadProgressChanged);
            client2.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client2_DownloadStringCompleted);
            client2.DownloadStringAsync(new Uri(Url), "blogtruyen");
        }
        private void LoadListNew(int PageIndex)
        {
            Global.PageNew.PageIndex = PageIndex;

            string Url = "http://m.blogtruyen.com/trangchu/?page=" + PageIndex.ToString();

            client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
            client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
            client.DownloadStringAsync(new Uri(Url), "blogtruyen");
        }
        void backroungWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.Dispatcher.BeginInvoke(() =>
            {

            }
            );
        }

        void backroungWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            if(loadNewSucess==true && loadListSucess==true)

                this.popup.IsOpen = false;
        }
        void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            if (e.UserState as string == "blogtruyen")
            {
            }
        }
        void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error == null && !e.Cancelled)
            {
                string MaxPage = GetStringBetweenText(e.Result, "selected=\"selected\">", "</option>");

                MaxPage = GetStringBetweenText(MaxPage, "/", "").Trim();

                Global.PageNew.PageMax = int.Parse(MaxPage);

                LoadListNew(GetStringBetweenText(e.Result, "<div class=\"page-home-list\">", " </select>"));

                loadNewSucess = true;
            }
        }

        public static string GetStringBetweenText(string strInputString, string strStart, string strEnd)
        {
            String szMid = "";
            int iPos1 = strStart == "" ? 0 : strInputString.IndexOf(strStart);
            if (iPos1 >= 0)
            {
                iPos1 += strStart.Length;
                int iPos2 = strEnd == "" ? strInputString.Length : strInputString.IndexOf(strEnd, iPos1);
                if (iPos2 >= iPos1)
                {
                    szMid = strInputString.Substring(iPos1, iPos2 - iPos1);
                }
            }
            return szMid;
        }

        private void ListMangaNew_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            GUI.ItemDetails item = ListMangaNew.SelectedItem as GUI.ItemDetails;
            if (item == null) return;
            Global.selectedItem = item;
            string navigate="";
            navigate += "Title=" + item.Title;
            navigate += "&UrlImage=" + HttpUtility.UrlEncode(item.UrlImage);
            navigate += "&Url=" +  HttpUtility.UrlEncode(item.Url);
            navigate += "&Description=" + item.Description;
            NavigationService.Navigate(new Uri("/GUI/ViewDetails.xaml?"+navigate, UriKind.Relative));
        }

        void client2_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            if (e.UserState as string == "blogtruyen")
            {
            }
        }
        void client2_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error == null && !e.Cancelled)
            {
                string MaxPage = GetStringBetweenText(e.Result, "selected=\"selected\">", "</option>");

                MaxPage = GetStringBetweenText(MaxPage, "/", "").Trim();

                Global.PageManga.PageMax = int.Parse(MaxPage);

                LoadListManga(GetStringBetweenText(e.Result, "<div class=\"danhsach\">", "<div class=\"paging-div\""));

                loadListSucess = true;

                this.popup.IsOpen = false;
            }
        }
        private void LoadListManga(string content)
        {
            ListManga.Items.Clear();
            string CheckContent = content;
            string line = "";
            line = GetStringBetweenText(CheckContent, "<a href=", "/a>");
            while (line != "")
            {

                string Title = HttpUtility.HtmlDecode(GetStringBetweenText(line, ">", "<"));
                string Url = "http://m.blogtruyen.com" + GetStringBetweenText(line, "\"", "\"");
                GUI.ItemCustom item = new GUI.ItemCustom();
                item.Title = Title;
                item.Url = Url;
                ListManga.Items.Add(item);

                CheckContent = GetStringBetweenText(CheckContent, "</span>", "");

                line = GetStringBetweenText(CheckContent, "<a href=", "/a>");
            }
        }

        private void ListManga_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            GUI.ItemCustom item = ListManga.SelectedItem as GUI.ItemCustom;
            if (item == null) return;
            GUI.ItemDetails selectedItem=new GUI.ItemDetails() { Title=item.Title,Url=item.Url,UrlImage="",Description="không có mô tả"};
            Global.selectedItem = selectedItem;
            string navigate = "";
            navigate += "Title=" + item.Title;
            navigate += "&UrlImage=";
            navigate += "&Url=" + HttpUtility.UrlEncode(item.Url);
            navigate += "&Description=";
            NavigationService.Navigate(new Uri("/GUI/ViewDetails.xaml?" + navigate, UriKind.Relative));
        }

        private void BtnFirst_Click(object sender, RoutedEventArgs e)
        {
            LoadListNew(1);
        }

        private void BtnNext_Click(object sender, RoutedEventArgs e)
        {
            if (Global.PageNew.PageIndex == Global.PageNew.PageMax) return;
            Global.PageNew.PageIndex++;
            LoadListNew(Global.PageNew.PageIndex);
        }

        private void BtnPreview_Click(object sender, RoutedEventArgs e)
        {
            if (Global.PageNew.PageIndex == 1) return;
            Global.PageNew.PageIndex--;
            LoadListNew(Global.PageNew.PageIndex);
        }

        private void BtnLast_Click(object sender, RoutedEventArgs e)
        {
            LoadListNew(Global.PageNew.PageMax);
            Global.PageNew.PageIndex = Global.PageNew.PageMax;
        }

        private void Grid_LostFocus(object sender, RoutedEventArgs e)
        {
            try
            {
                var Page = ((TextBox)e.OriginalSource).Text;

                if (Page != null)
                {
                    int PageNumber;

                    if (int.TryParse(Page, out PageNumber))
                    {
                        if (PageNumber <= Global.PageNew.PageMax && PageNumber > 0)
                        {
                            Global.PageNew.PageIndex = PageNumber;
                            LoadListNew(Global.PageNew.PageIndex);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                
            }
        }

        private void PageNumberNew_GotFocus(object sender, RoutedEventArgs e)
        {
            ((TextBox)e.OriginalSource).Text="";
        }

        private void MangaBtnFirst_Click(object sender, RoutedEventArgs e)
        {
            LoadMangaList(1);
        }

        private void MangaBtnPreview_Click(object sender, RoutedEventArgs e)
        {
            if (Global.PageManga.PageIndex == 1) return;
            Global.PageManga.PageIndex--;
            LoadMangaList(Global.PageManga.PageIndex);
        }

        private void MangaBtnNext_Click(object sender, RoutedEventArgs e)
        {
            if (Global.PageManga.PageIndex == Global.PageManga.PageMax) return;
            Global.PageManga.PageIndex++;
            LoadMangaList(Global.PageManga.PageIndex);
        }

        private void MangaBtnLast_Click(object sender, RoutedEventArgs e)
        {
            LoadMangaList(Global.PageManga.PageMax);
            Global.PageManga.PageIndex = Global.PageManga.PageMax;
        }

        private void MangaBtnSearch_Click(object sender, RoutedEventArgs e)
        {
            Popup popup = new Popup();
            popup.Height = 200;
            popup.Width = 480;
            //popup.VerticalOffset = 100;
            GUI.InputControls control = new GUI.InputControls();
            control.title.Text = "Nhập vào nội dung bạn muốn tìm:";
            popup.Child = control;
            popup.IsOpen = true;


            control.BtnOk.Click += (s, args) =>
            {
                popup.IsOpen = false;

                SearchManga(control.txtInput.Text);
            };

            control.btnCancel.Click += (s, args) =>
            {
                popup.IsOpen = false;
            };

            control.grid2.Tap += (s, args) =>
            {
                popup.IsOpen = false;
            };
            control.txtInput.GotFocus += (s, args) =>
            {
                control.txtInput.Text = "";
            };
        }
        private void SearchManga(string keyword)
        {
            string Url = "http://m.blogtruyen.com/timkiem/?truyen=" + keyword;

            client3.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client2_DownloadProgressChangedSearch);
            client3.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client2_DownloadStringCompletedSearch);
            client3.DownloadStringAsync(new Uri(Url), "blogtruyen");
        }
        void client2_DownloadProgressChangedSearch(object sender, DownloadProgressChangedEventArgs e)
        {
            if (e.UserState as string == "blogtruyen")
            {
            }
        }
        void client2_DownloadStringCompletedSearch(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error == null && !e.Cancelled)
            {
                LoadListSearch(GetStringBetweenText(e.Result, "<div class=\"danhsach\">", " <br />"));
            }
        }
        void LoadListSearch(string content)
        {
            ListManga.Items.Clear();
            string CheckContent = content;
            string line = "";
            line = GetStringBetweenText(CheckContent, "<a href=", "/a>");
            while (line != "")
            {

                string Title = HttpUtility.HtmlDecode(GetStringBetweenText(line, "'>", "<"));
                string Url = "http://m.blogtruyen.com" + GetStringBetweenText(line, "\"", "\"");
                GUI.ItemCustom item = new GUI.ItemCustom();
                item.Title = Title;
                item.Url = Url;
                ListManga.Items.Add(item);

                CheckContent = GetStringBetweenText(CheckContent, line, "");

                line = GetStringBetweenText(CheckContent, "<a href=", "/a>");
            }
        }
    }
}